import redis.clients.jedis.Jedis;

import java.util.Random;

public class PhoneCode {

  public static void main(String[] args) {

    // 模拟验证码发送
    verifyCode("18672592357" );

//    String code = getCode();
//    System.out.println(code);
  }

  public static void verifyCode(String phone) {
    Jedis jedis = new Jedis("192.168.101.17", 6379);

    // 拼接 key
    // 手机发送次数 key
    String countKey = "VerifyCode" + phone + ":count";
    // 验证码 key
    String codeKey = "VerifyCode" + phone + ":code";

    // 每个手机每天只能发送 3 次
    String count = jedis.get(countKey);
    if(count == null) {
      // 没有发送次数，第一次发送
      jedis.setex(countKey, 24 * 60 * 60L, "1");
    } else if(Integer.parseInt(count) <= 2) {
      jedis.incr(countKey);
    } else if(Integer.parseInt(count) > 2) {
      System.out.println("今天发送次数已经达到3次");
      jedis.close();
    }

    // 发送的验证码放到 redis 里面去
    String vcode = getCode();
    jedis.setex(codeKey, 120L, vcode);
    jedis.close();
  }

  public static void getRedisCode(String phone, String code) {
    Jedis jedis = new Jedis("192.168.101.17", 6379);
    String codeKey = "VerifyCode" + phone + ":code";

    String redisCode = jedis.get(codeKey);
    if(redisCode.equals(code)) {
      System.out.println("成功");
    } else {
      System.out.println("失败");
    }
  }

  // 生成 6 位数字验证码
  public static String getCode() {
    Random random = new Random();
    String code = "";
    for (int i = 0; i < 6; i++) {
      int i1 = random.nextInt(10);
      code += i1;
    }
    return code;
  }
}
